<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiAlarmApi } from '#/api/moxi/aialarm';
import { getFalseAlarmPage, falseAlarm } from '#/api/moxi/aialarm';
import dayjs from 'dayjs';
import { ref, reactive } from 'vue';
import { confirm, DocAlert, Page, useVbenDrawer } from '@vben/common-ui';
import { Card, message } from 'ant-design-vue';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { $t } from '#/locales';
import { DICT_TYPE, getDictLabel } from '#/utils';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';

// 误报抽屉表单数据
interface FormState {
  falseAlarmDesc: string;
}

const formState = reactive<FormState>({
  falseAlarmDesc: '',
});
const open = ref<boolean>(false);

const formRef = ref();
// 误报内容
const alarmId = ref<number>();
const showModal = (row: any) => {
  alarmId.value = row.id;
  open.value = true;
};

// 误报抽屉提交
const handleOk = async (e: MouseEvent) => {
  try {
    const values = await formRef.value.validate();
    // 验证成功，处理表单数据
    console.log('表单验证成功:', values);

    // 这里可以添加提交数据的逻辑
    const res = await falseAlarm({
      id: alarmId.value,
      falseAlarmDesc: formState.falseAlarmDesc,
    });
    if (res) {
      open.value = false;
      message.success('提交成功');
      formState.falseAlarmDesc = '';
      onRefresh();
    } else {
      message.error('提交失败');
    }
  } catch (error) {
    // 验证失败，显示错误信息
    console.log('表单验证失败:', error);
  }
};

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 编辑用户 */
function handleEdit(row: AiAlarmApi.AiAlarm) {
  console.log($t('common.edit'));
  formDrawerApi.setData(row).open();
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: AiAlarmApi.AiAlarm[];
}) {
  checkedIds.value = records.map((item) => item.id as number);
}

// /** 更新用户状态 */
// async function handleStatusChange(
//   newStatus: number,
//   row:AiAlarmApi.AiAlarm,
// ): Promise<boolean | undefined> {
//   return new Promise((resolve, reject) => {
//     confirm({
//       content: `你要将${row.username}的状态切换为【${getDictLabel(DICT_TYPE.COMMON_STATUS, newStatus)}】吗？`,
//     })
//       .then(async () => {
//         // 更新用户状态
//         const res = await updateUserStatus(row.id as number, newStatus);
//         if (res) {
//           // 提示并返回成功
//           message.success($t('ui.actionMessage.operationSuccess'));
//           resolve(true);
//         } else {
//           reject(new Error('更新失败'));
//         }
//       })
//       .catch(() => {
//         reject(new Error('取消操作'));
//       });
//   });
// }

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          const params = {
            pageNo: page.currentPage,
            pageSize: page.pageSize,
          };
          if (formValues.typeCode) {
            (params as any).typeCode = formValues.typeCode;
          }
          if (formValues.objName) {
            (params as any).objName = formValues.objName;
          }
          if (formValues.alarmTime && formValues.alarmTime.length > 0) {
            (params as any).alarmTime =
              formValues.alarmTime[0] + ',' + formValues.alarmTime[1];
          }
          return await getFalseAlarmPage(params);
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: { code: 'query' },
      search: true,
    },
  } as VxeTableGridOptions<AiAlarmApi.AiAlarm>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Page auto-content-height>
    <FormDrawer @success="onRefresh" />
    <ResetPasswordDrawer @success="onRefresh" />
    <AssignRoleDrawer @success="onRefresh" />
    <ImportDrawer @success="onRefresh" />
    <Grid table-title="用户列表">
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['system:user:update'],
              onClick: handleEdit.bind(null, row),
            },
          ]"
        />
      </template>
    </Grid>

    <a-modal v-model:open="open" title="误报" @ok="handleOk">
      <a-form :model="formState" ref="formRef">
        <a-form-item
          label="误报说明"
          name="falseAlarmDesc"
          :rules="[{ required: true, message: '请填写误报说明' }]"
        >
          <a-textarea v-model:value="formState.falseAlarmDesc" />
        </a-form-item>
      </a-form>
    </a-modal>
  </Page>
</template>
